package com.hyt.it.ogt.kq.service.gov.den;

import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.it.ogt.kq.service.gov.feign.tps.GovTpsClient;
import com.hyt.it.ogt.kq.service.model.entity.CandidatePhoto;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;

/**
 * @ClassName : PicCompress
 * @Description : 图片压缩处理工具类
 * @Author : wanggang
 * @Date: 2021-11-18
 * @Version 1.0
 **/
@Slf4j
@Component
public class PicCompressUtil {

    @Resource
    private GovTpsClient tpsClient;

    /**
     * 按质量压缩
     */
    public static void compressByQuality(String sourceFilePath, String targetFilePath, float scaleParam, float qualityParam) throws Exception {
        Thumbnails.of(new File(sourceFilePath)).scale(scaleParam) // 图片大小（长宽）压缩比例 从0-1，1表示原图，如：1f
                .outputQuality(qualityParam) // 图片质量压缩比例 从0-1，越接近1质量越好，如：0.5f
                .toOutputStream(new FileOutputStream(targetFilePath));
    }


    /**
     * 按比例缩放
     */
    public static void compressByProp(String sourceFilePath, String targetFilePath, float propParam, float qualityParam) throws Exception {
        Thumbnails.of(new File(sourceFilePath)).scale(propParam) // 图片大小（长宽）压缩 从0按照，如：0.5f
                .outputQuality(qualityParam) // 图片质量压缩比例 从0-1，越接近1质量越好，如：0.5f
                .toOutputStream(new FileOutputStream(targetFilePath));
    }

    /**
     * 按大小缩放
     */
    public static void compressBySize(String sourceFilePath, String targetFilePath, int width, int hight) throws Exception {
        Thumbnails.of(new File(sourceFilePath))
                .forceSize(width, hight) //不保持图片比例
                .toOutputStream(new FileOutputStream(targetFilePath));
    }

    /**
     * 按大小和比例缩放
     */
    public static void compressByPropAndSize(String sourceFilePath, String targetFilePath, int width, int hight) throws Exception {
        Thumbnails.of(new File(sourceFilePath))
                .size(width, hight) // 图片比例不变
                .toOutputStream(new FileOutputStream(targetFilePath));
    }

    /**
     * 旋转
     */

    public static void compressRotate(String sourceFilePath, String targetFilePath, int width, int hight, float rotateParam) throws Exception {
        Thumbnails.of(new File(sourceFilePath))
                .forceSize(width, hight)
                .rotate(rotateParam) //向右旋转，如：90f
                .toOutputStream(new FileOutputStream(targetFilePath));
    }

    /**
     * 裁剪
     */

    public static void compressCut(String sourceFilePath, String targetFilePath, int width, int hight, boolean flag) throws IOException {
        Thumbnails.of(sourceFilePath)
                .sourceRegion(Positions.CENTER, width, hight) //位置，宽，高
                .size(width, hight)
                .keepAspectRatio(flag)
                .toFile(targetFilePath);
    }

    /**
     * 压缩腾讯云COS图片文件，并存储至指定路径（异步）
     * @param officeId 机构id
     * @param candidatePhoto 考生照片
     * @param targetPath 压缩后的图片存储的路径
     * @return 压缩图片结果路径
     */
    @Async("picCompressAsyncExecutor")
    public CompletableFuture<CandidatePhoto> compressTencentCosPhotoByAsync(String officeId, CandidatePhoto candidatePhoto, String targetPath) {
        log.info("【开始】多线程压缩腾讯云COS图片文件，考生id: {}，待压缩图片文件绝对路径: {}", candidatePhoto.getCandidateId(), candidatePhoto.getPhotoPath());
        try {
        	ApiResponse<String> result = tpsClient.compressTencentCosPhoto(officeId, candidatePhoto.getPhotoPath(), targetPath);
        	if(null != result &&  StringUtils.isNotEmpty(result.getData())) {
        		candidatePhoto.setPhotoPath(result.getData());
        	}
		} catch (Exception e) {
			log.info("## compressTencentCosPhoto error", e);
		}
        log.info("【结束】多线程压缩腾讯云COS图片文件，考生id: {}，压缩后图片文件绝对路径: {}", candidatePhoto.getCandidateId(), candidatePhoto.getPhotoPath());
        return CompletableFuture.completedFuture(candidatePhoto);
    }

    /**
     * 压缩腾讯云COS图片文件，并存储至指定路径（异步）
     * @param officeId 机构id
     * @param candidatePhoto 考生照片
     * @param targetPath 压缩后的图片存储的路径
     * @return 压缩图片结果路径
     */
    public void compressTencentCosPhoto(String officeId, CandidatePhoto candidatePhoto, String targetPath) {
        log.info("【开始】多线程压缩腾讯云COS图片文件，考生id: {}，待压缩图片文件绝对路径: {}", candidatePhoto.getCandidateId(), candidatePhoto.getPhotoPath());
        try {
        	ApiResponse<String> result = tpsClient.compressTencentCosPhoto(officeId, candidatePhoto.getPhotoPath(), targetPath);
        	if(null != result &&  StringUtils.isNotEmpty(result.getData())) {
        		candidatePhoto.setPhotoPath(result.getData());
        	}
		} catch (Exception e) {
			log.info("## compressTencentCosPhoto error", e);
		}
        log.info("【结束】多线程压缩腾讯云COS图片文件，考生id: {}，压缩后图片文件绝对路径: {}", candidatePhoto.getCandidateId(), candidatePhoto.getPhotoPath());
    }

}
